package com.duangxt.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: duangxt
 * @Title:
 * @ClassName: UrlUtils.java
 * @Description:
 * @Date: Create in 2020/5/21 15:45:48
 * @Version: V0.0.1
 */
public class UrlUtils {

    private static final String DEFAULT_ENCODING = "UTF-8";

    /**
     * only 'UTF-8'
     * @param s String
     * @return encode string, source string or ""
     */
    public static String encode(String s){
        return encode(s, true);
    }

    /**
     * only 'UTF-8'
     * @param s String
     * @return decode string, source string or ""
     */
    public static String decode(String s){
        return encode(s, false);
    }

    private static String encode(String s, boolean isEncode){
        try {
            if(isEncode)
                s = URLEncoder.encode(s, DEFAULT_ENCODING);
            else s = URLDecoder.decode(s, DEFAULT_ENCODING);
        }
        catch (NullPointerException e){
            s = "";
        }
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 从可以正常访问的链接中获取实际域名<br/>
     * 例：<pre>
     *     https://www.abc.com/s?wd=a      ==>  www.abc.com
     *     http://127.0.0.1/myweb          ==>  127.0.0.1
     *     http://127.0.0.1:8080/myweb     ==>  127.0.0.1
     *     http://www.abc.com.cn/          ==>  www.abc.com.cn
     * </pre>
     * @param url
     * @return
     */
    public static String getUrlHostname(String url){
        return getUrlHostname(url, false);
    }

    public static String getUrlHostname(String url, boolean showPort) {
        if ("".equals(url = MyStringUtils.deleteSpace(url))) return "";

        if (0 < url.indexOf("://")) // 去掉协议声明
            url = url.substring(url.indexOf("://") + 3);
        url = url.split("\\?")[0]; // 参数之前
        url = url.split("/")[0]; // 路由之前，只留根域名
        if (!showPort) url = url.split(":")[0]; // 去掉端口号

        return url;
    }

    public static String urlSetParam(String url, String strParam){
        url = MyStringUtils.trim(url);
        if(!url.endsWith("?")) url += "?";

        strParam = MyStringUtils.trim(strParam);
        strParam = strParam.replaceAll("\\?","");
        // if(strParam.startsWith("?")) strParam = strParam.substring(1);
        if(strParam.startsWith("&"))
            strParam = strParam.substring(1);

        return url + strParam;
    }

    public static String urlSetParam(String url, Map<String, Object> params, boolean encode){
        StringBuffer sb = new StringBuffer();
        Iterator<Map.Entry<String, Object>> iter = params.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry<String, Object> entry = iter.next();
            Object value = entry.getValue();
            if(encode) value = encode((String) value);
            sb.append("&").append(entry.getKey()).append("=").append(value);
        }
        String strParam = sb.toString();
        if(1<strParam.length()) strParam.substring(1);

        return urlSetParam(url, strParam);
    }

    public static String urlSetParam(String url, Map<String, Object> params){
        return urlSetParam(url, params, false);
    }
}
